const { Service} = require('egg')
const path = require('path');
const fes = require('fs-extra');
class ToolService extends Service{
    async merg(filePath,hash,size){
        const chunkDir = path.resolve(this.config.UPLOAD__FILE,hash);
        let chunks = await fes.readdir(chunkDir);
        chunks.sort((a,b)=>a.split('-')[1]-b.split('-')[1])
        chunks = chunks.map(cp=>path.resolve(chunkDir,cp))
        await this.mergChunks(chunks,filePath,size);
    }
    async mergChunks(files,dist,size){
        const pipStrem = (filePath,writeStream)=>new Promise(resolve=>{
            const readStream = fes.createReadStream(filePath);
            readStream.on('end',()=>{
                fes.unlinkSync(filePath);
                resolve()
            })
            readStream.pipe(writeStream);
        })
        await Promise.all(
            files.map((file,index)=>{
                pipStrem(file,fes.createWriteStream(dist,{
                    start:index*size,
                    end:(index+1)*size
                }))
            })
        )
    }
}

module.exports = ToolService;